<?php

namespace app\uapi\controller;

use app\admin\model\KnscyOrders;
use app\admin\model\KnscyOrderTicket;
use app\admin\model\KnscyTicketOut;
use app\admin\model\KnscyTicketOutLogs;
use app\admin\model\KnscyTickets;
use app\common\controller\ApiController;
use app\common\service\GoodService;
use app\common\service\WeginService;
use think\facade\Db;

class Tickets extends ApiController
{
    public static $needLoginAction = [
        'userTickets',  //用户的门票
        'userCard', //用户的卡
        'activeTicketOut', //用户自己激活卡
    ];

    public function userTickets()
    {
        $limit = $this->request->post('limit', 10);
        $page = $this->request->post('page', 1);
        //订单查询
        $datalist = KnscyTicketOut::where('sort', ">=", 0)
            ->where('ticket_type', 1)
            ->where('status', 1)
            ->with('orderInfo')
            ->where('user_id', $this->user_id)
            //订单的total_price是模型的属性，通过别名查询可以获取属性值
            ->order(Db::raw('sort=0,sort asc,id desc'))
            ->paginate(
                [
                    'list_rows' => $limit,
                    'page' => $page,
                ]
            )->each(function ($item) {
                $item['select_day2'] = date('Y.m.d', strtotime($item['select_day']));
                $item['tag_id'] = 1;
                $item['tag'] = '待出行';
                if ($item->is_end) {
                    $item['tag_id'] = 2;
                    $item['tag'] = '已用';
                }
                if ($item->is_end == 0) {
                    if (strtotime($item->select_day . " 23:59:59") < time()) {
                        $item['tag_id'] = 3;
                        $item['tag'] = '过期失效';
                    }
                }
            });
        $this->success('success', $datalist);
    }

    public function userCard()
    {
        $limit = $this->request->post('limit', 10);
        $page = $this->request->post('page', 1);
        //订单查询
        $datalist = KnscyTicketOut::where('sort', ">=", 0)
            ->whereIn('ticket_type', [2, 3])
            ->where('status', 1)
            ->with('orderInfo')
            ->where('user_id', $this->user_id)
            //  ->where('end_time','<>', 'NULL' )
            //订单的total_price是模型的属性，通过别名查询可以获取属性值
            ->order(Db::raw(' id desc'))
            ->paginate(
                [
                    'list_rows' => $limit,
                    'page' => $page,
                ]
            )->each(function ($item) {
                $this->ticket_out_format($item);
            });
        $this->success('success', $datalist);
    }

    protected function ticket_out_format(&$item)
    {
        $item['qrcode_value'] = 'ticketOutQrcode=' . $item['ticket_sn'];
        $types = KnscyTickets::getTicketTypeList();
        $item['ticket_type_name'] = $types[$item['ticket_type']] ?? '';
        $item['ticket_total_count'] = $item['ticket_type'] == 3 ? '不限制（次）' : $item['total_count'] . ' 次';
        //有效期
        if ($item->end_time) {
            $start_time = date('Y.m.d', strtotime('-1 year', strtotime($item['end_time'])));
            $item['select_day2'] = $start_time . "至" . date('Y.m.d', strtotime($item['end_time']));

        } else {
            $item['select_day2'] = "~~至~~";
        }
        $item['tag_id'] = 1;
        $item['tag'] = '有效';
        if ($item->is_end) {
            $item['tag_id'] = 2;
            $item['tag'] = '已用完';
        }
        if ($item->is_end == 0) {
            if (empty($item->end_time)) {
                $item['tag_id'] = 4;
                $item['tag'] = '待激活';

            } else {
                if (strtotime($item->end_time) < time()) {
                    $item['tag_id'] = 3;
                    $item['tag'] = '过期失效';
                }
            }


        }
    }

    /**
     * 门票年卡的详情
     * @return void
     *
     */
    public function ticketOutDetails()
    {
        $id = $this->request->post('id');
        $out = KnscyTicketOut::where('id', $id)->find();
        if (empty($out)) {
            $this->error('error1');
        }
        $order = KnscyOrders::where('order_no', $out['order_no'])->field("*,order_money as total_price")->find();
        if (empty($order)) {
            $this->error('error2');
        }

        $detail = KnscyOrderTicket::where('order_id', $order['id'])->find();
        if (empty($detail)) {
            $this->error('error3');
        }
        $ticket = $detail['ticket_json'];
        $ticket['address'] = sysconfig('company', 'address') ?? '请设置门票地址';
        //关联 的文案
        $ticket['remark_list'] = GoodService::ticketInfos($ticket['remark']);
        //
        $peoples = $detail['people_json'];
        $logs = KnscyTicketOutLogs::where('ticket_sn', $out['ticket_sn'])->select();
        $this->ticket_out_format($out);
        $this->success('success', [
            'order' => $order,
            'detail' => $detail,
            'ticket' => $ticket,
            'peoples' => $peoples,
            'ticket_out' => $out,
            'out_log' => $logs
        ]);
    }

    /**
     * 用户自己激活卡
     */
    public function activeTicketOut()
    {
        $ticket_sn = $this->request->post('ticket_sn');
        $ticket_out = KnscyTicketOut::where('ticket_sn', $ticket_sn)
            ->where('sort', '>', -1)
            ->where('user_id', $this->user_id)->find();
        if (empty($ticket_out)) {
            $this->error('门票（或卡）数据不存在', [], 1);
        }

        $update['sort'] = 1; //扫码订单激活了卡
        $update['end_time'] = date('Y-m-d H:i:s', strtotime('+1 year'));
        KnscyTicketOut::update($update, ['ticket_sn' => $ticket_sn]);

        $this->success('激活成功', $ticket_out);
    }
}